package de.mauandmau;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

public abstract class Client implements Runnable {
	// CLIENT CONNECTION STATE
	boolean connected = true;
	// The Server's IP
	String ip = "";
	// The Server's SocketPort
	int port = 4444;
	Socket requestSocket;
	InputStreamReader isr;
	BufferedReader br;
	StringBuilder returnStringBuffer = new StringBuilder();
	private Context context;
	BufferedOutputStream bos;
	private Handler handler = new Handler();

	public Client(Context context) {
		this.context = context;
	}

	public void run() {
		ip = Start.getIPFromEditText();
		try {
			this.requestSocket = new Socket(ip, port);
			bos = new BufferedOutputStream(requestSocket.getOutputStream());
			isr = new InputStreamReader(this.requestSocket.getInputStream(),
					"UTF-8");
			br = new BufferedReader(isr);
			while (connected) {
				String line = null;
				while ((line = br.readLine()) != null) {
					handleMessage(line);
				}
			}
		} catch (Exception e) {
			Log.e(Utils.TAG, "Fehler", e);
		}
	}

	protected abstract void handleMessage(String string);

	public void sendCommandToServer(String commandString) {
		commandString += "\n";
		try {
			bos.write(commandString.getBytes("UTF-8"));
			bos.flush();
		} catch (IOException e) {
			Log.e(Utils.TAG, "error", e);
		}
	}

	public void destroy() {
		try {
			if (bos != null) {
				bos.close();
			}
			if (requestSocket != null) {
				requestSocket.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
